<?php

namespace App\Http\Controllers\User;

use App\Models\Composition;
use App\Models\Content;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Validator;

class ContentController extends Controller{
    //前端展示
    public function show(){
        $id =  explode('/',url()->current())[6];
        $brands = Content::where('com_id',$id)->where('partid',Auth::user()->partid)->where('active','0')->paginate(10);
        return view('akl.Aikla.Content-index',compact('brands'));
    }
    //后台展示
    public function look($com_id){
        $cons = Content::where('com_id',$com_id)->where('partid',Auth::user()->partid)->where('active','0')->paginate(10);
        return view('akl.Admin.content_index',compact('cons'));
    }
    //返回编辑页面
    public function edit($al_id){
        $con = Content::where('al_id',$al_id)->first();
        return view('akl.Admin.Content_edit',compact('con'));
    }
    //提交更新数据
    public function update(Request $request,$al_id){
        $input = Input::except('_token','_method','file');
        if($request->get('imgs')[0]) $input['al_img'] = $request->get('imgs')[0];
        $state = Content::where('al_id',$al_id)->update($input);
        if ($state){
            return redirect(url('Admin/Content/look/'.$input['com_id']));
        }else{
            return back()->withErrors('分类内容更新失败!');
        }
    }
    //返回添加页面
    public function create(){
        $coms = Composition::all();
        return view('akl.Admin.Content_add',compact('coms'));
    }
    //添加提交数据
    public function store( Request $request){
        $input = Input::except('_token');
        $rules = [
            'al_name'=>'required',
        ];
        $mes = [
            'al_name.required'=>'分类名不能为空!',
        ];
        $va =  Validator::make($input,$rules,$mes);
        if ($va->passes()){
            $input['partid'] = Auth::user()->partid;
            $input['al_img'] = $request->get('imgs')[0];
//            dd($input);
            $state = Content::create($input);
            if ($state){
                return redirect(url('Admin/Composition/index'));
            } else{
                return back()->withErrors('数据提交失败,请稍后再试!');
            }
        }else{
            return back()->withErrors($va);
        }

    }
    public function delete($id){
//        dd($id);
        $state = Content::where('al_id',$id)->where('partid',Auth::user()->partid)->update(['active'=>'1']);
        if($state==1){
            return redirect(url('Admin/Composition/index'));
        }else{
            return back()->withErrors('内容删除失败');
        };
    }
    public function showAll($id){
        $state = Content::where('al_id',$id)->first();
        $img = $state->al_cons;
        return view('akl.Aikla.img',compact('img'));
    }

}